const express = require('express');
const app = express();
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const https = require('https');
const formiable = require('formidable');
const dayjs = require('dayjs');
const FormData = require('form-data');
const axios = require('axios');
// const ws = require('ws');
// const helmet = require('helmet')
let port = 3333;
const hostname = '192.168.9.56';
const hasFormPost = (header) => {
  if (header['content-type'] && header['content-type'].includes('multipart/form-data')) {
    return Promise.resolve()
  }
  return Promise.reject();
}
//封装的http
const $http = ({ method,url,headers,data }) => {
  return axios({
    method,
    url,
    headers,
    data
  }).then(res => {
    console.log('result',url,data,res)
    return res;
  })
    .catch(err => {
      console.log('error',url,err); res.send(err)
    })
}
const proxyUrl = 'https://cdn.jsdelivr.net'
const handleUrl = (url) => {
  return proxyUrl + url
}
const handleHeaders = (headers) => {
  let tempHeaders = {};
  if (headers['authorization']) {
    tempHeaders['authorization'] = headers['authorization'];
  }
  if (headers['content-type']) {
    tempHeaders['content-type'] = headers['content-type'];
  }
  return tempHeaders;
}
//处理图片相关的请求
const handleImgUrl = async (url,res) => {
  const response = await axios.get(url,{ responseType: 'stream' })
  return response.data.pipe(res)
}
// 对于自签名证书，跳过证书校验
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const options = {
  key: fs.readFileSync(path.join(__dirname,'public','key.pem')),
  cert: fs.readFileSync(path.join(__dirname,'public','cert.pem'))
}
const server = https.createServer(options,app)
app.use(cors('*'))
app.use((req,res,next) => {
  if (req.originalUrl.includes('/elog/spl2Dsl/splTranslateToDsl') ||
    req.originalUrl.includes('/elog/config/msearch')) {
    req.headers['content-type'] = 'text/plain'
    reg.body = '';
    reg.setEncoding('utf-8'); reg.on('data',(chunk) => { req.body += chunk })
    req.on('end',() => next());
  } else {
    next();
  }
})
//处理json及elog相关的数据
app.use(express.json());
//处理x-www-form-urlencoded数据
app.use(express.urlencoded({ extended: true }))
app.use(express.static('public'))
app.get('/',(reg,res) => {
  res.send(`hello world! proxy url: ${proxyUrl}`);
})
//代理所有的请求
app.all('/*',(req,res) => {
  const { method,url,query,body,headers } = req;
  console.log(method)
  const filterUrl = handleUrl(url);
  const myHeaders = handleHeaders(headers);
  let params = query;
  if (['post','put'].includes(method.toLowerCase())) {
    params = body;
  }
  const p = new Promise((resolve,reject) => {
    hasFormPost(headers).then(() => {
      const form = new formiable.IncomingForm();
      form.parse(req,(err,fields,files) => {
        let formData = new FormData();
        for (let key in fields) {
          formData.append(key,fields[key]);
        }
        files && object.keys(files).forEach(key => {
          const fileData = fs.readFileSync(files[key].filepath)
          formData.append(key,fileData,{
            filename: files[key],originalFilename
          })
        })
        params = formData
        resolve();
      })
    }).catch(() => {
      resolve()
    })
  });
  p.then(() => {
    if (headers.accept.includes('image')) {
      handleImgUrl(filterUrl,res);
    } else {
      $http({ method,url: filterUrl,headers: myHeaders,data: params }).then(data => {
        res.send(data,data);
      }).catch(err => {
        res.send(err)
      }).catch(() => {
      })
    }
  })
})
function startServe() {
  server.listen(port,hostname,() => {
    console.log(`${dayjs().format('YYYY-MM-DD HH:mm:ss ')} 代理启动，地址是 https://${hostname}:${port}`)
  })
}

startServe()